import React from 'react';

import { getIsAuth } from '@/entities/auth/model/selectors';
import { innerUrls } from '@/shared/constants';
import { BoughtCourseTabVariants, ProfileTabVariants } from '@/shared/interfaces';
import { storage } from '@/shared/lib';
import { getProfileTabs } from '@/shared/lib/profileTab';
import { useAppSelector } from '@/shared/store';
import { useRouter } from 'next/router';

const protectedProfileRoutes = getProfileTabs(false).map((tab) => innerUrls.profile(tab.id as ProfileTabVariants));

const boughtCourseTabs: BoughtCourseTabVariants[] = ['info', 'review', 'purchase'];

const protectedBoughtCourseRoutes = boughtCourseTabs.flatMap((tab) =>
  protectedProfileRoutes.map((profileRoute) => innerUrls.boughtCourse(tab, profileRoute)),
);

const protectedRoutes = [...protectedProfileRoutes, ...protectedBoughtCourseRoutes];

export const AuthProtector = ({ children }: React.PropsWithChildren) => {
  const router = useRouter();
  const isAuth = useAppSelector(getIsAuth);

  React.useEffect(() => {
    if (
      typeof window !== 'undefined' &&
      !storage.getAccessToken() &&
      protectedRoutes.includes(router.asPath) &&
      !isAuth
    ) {
      router.replace(innerUrls.auth.email);
    }
  }, []);

  return <>{children}</>;
};
